package org.example.project.service.impl;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.example.project.entity.RecognizeResult;
import org.example.project.service.PlantRecognizeService;
import org.example.project.util.ResponseCode;
import org.example.project.util.ResponseData;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author linky
 */
@Service("plantRecognizeService")
public class PlantRecognizeServiceImpl implements PlantRecognizeService {

    @Override
    public RecognizeResult recognize( String imagePath) throws IOException {


        String pythonExecutable = "D:\\Anaconda3\\envs\\pytorch\\python.exe";
        String pythonScript = "D:\\PythonProject\\test\\predict.py";
        String[] arguments = new String[] {pythonExecutable, pythonScript, imagePath};

        RecognizeResult result = new RecognizeResult();

        try {
            // 设置本地工作目录
            File workingDirectory = new File("D:\\PythonProject\\test");

            // 启动python脚本
            ProcessBuilder pb = new ProcessBuilder(arguments);
            pb.directory(workingDirectory);
            pb.redirectErrorStream(true);
            Process proc = pb.start();
            // Process proc = Runtime.getRuntime().exec(arguments);
            // 用输入输出流来截取结果
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                try{
                    JSONObject json = JSONObject.parseObject(line);
                    if (json != null){
                        result.setFileName(json.getString("fileName"));
                        result.setName(json.getString("result"));
                        result.setAccuracy(json.getString("accuracy"));
                        result.setResult("识别成功");
                    }
                    System.out.println(json);
                }catch(JSONException e){
                    System.out.println( e.getMessage());
                    result.setResult("识别失败");
                }

            }
            in.close();
            //waitFor是用来显示脚本是否运行成功，1表示失败，0表示成功，还有其他的表示其他错误
            int re = proc.waitFor();
            System.out.println(re);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        //返回识别结果
        return result;
    }
}